<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    v-model="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="userForm" @keyup.enter="dataFormSubmit()" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="dataForm.username" placeholder="登录帐号"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.comfirmPassword" type="password" placeholder="确认密码"></el-input>
      </el-form-item>
      <el-form-item label="角色" size="mini" prop="roleIdList">
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox v-for="role in roleList" :key="role['roleId']" :label="role['roleId']">{{ role['roleName'] }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, nextTick } from 'vue'
import { userInfo, saveOrUpdate, roleSelect } from '@/api/sys/user'
import { ElMessage } from 'element-plus'
import type { ElForm } from 'element-plus'

// 弹窗显示
let visible = $ref(false)
// 角色列表
let roleList = $ref([])
// 表单数据
const dataForm = reactive({
  id: 0,
  username: '',
  password: '',
  comfirmPassword: '',
  salt: '',
  openid: '',
  headimgurl: '',
  roleIdList: [],
  status: 1
})
// 校验密码
var validatePassword = (rule: any, value: any, callback: any) => {
  if (!dataForm.id && !/\S/.test(value)) {
    callback(new Error('密码不能为空'))
  } else {
    callback()
  }
}
// 校验重复密码
var validateComfirmPassword = (rule: any, value: any, callback: any) => {
  if (!dataForm.id && !/\S/.test(value)) {
    callback(new Error('确认密码不能为空'))
  } else if (dataForm.password !== value) {
    callback(new Error('确认密码与密码输入不一致'))
  } else {
    callback()
  }
}
// 表单校验规则
const dataRule = reactive({
  userName: [
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ],
  password: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  comfirmPassword: [
    { validator: validateComfirmPassword, trigger: 'blur' }
  ]
})
// 表单
const userForm = $ref<InstanceType<typeof ElForm>>()
// 初始化函数
const init = async (id: number) => {
  dataForm.id = id || 0
  // 获取角色列表
  const { data } = await roleSelect()
  if (data.code === 0) {
    roleList = data.list
  }
  // 显示弹窗
  visible = true
  await nextTick()
  // 表单重置
  userForm.resetFields()
  if (id) {
    userInfo({id: id}).then(({ data }) => {
      if (data && data.code === 0) {
        dataForm.id = data.user.id
        dataForm.username = data.user.username
        dataForm.password = data.user.password
        dataForm.status = data.user.status
        dataForm.roleIdList = data.user.roleIdList
      } else {
        ElMessage.error(data.msg)
      }
    })
  }
}

// 提交表单
const dataFormSubmit = () => {
  userForm.validate((valid: boolean) => {
    if (valid) {
      saveOrUpdate(dataForm).then(({ data }) => {
        if (data && data.code === 0) {
          ElMessage({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              visible = false
              emit('refreshDataList')
            }
          })
        } else {
          ElMessage.error(data.msg)
        }
      })
    }
  })
}
// 接收函数
const emit = defineEmits(['refreshDataList'])
// 暴露函数
defineExpose({ init })
</script>